import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;


public class Simulator extends Thread {

	Process            littleguy;
	BufferedReader     stdout;
	OutputStreamWriter stdin;
	ArrayList<Player>  players;

	public Simulator(ArrayList<Player> frobernate){
		ProcessBuilder pb = new ProcessBuilder("C:\\Users\\Steve Donaldson Jr\\Documents\\JCU\\CS470 - Software Engineering Project\\workspace\\cerrano\\cerrano-cpp\\bin\\sim-cerrano.win32.exe");

		this.players = frobernate;

		try {
			this.littleguy = pb.start();

			this.stdout = new BufferedReader(
					new InputStreamReader(
							this.littleguy.getInputStream()
					)
			);
			this.stdin = new OutputStreamWriter( this.littleguy.getOutputStream() );

			this.setup();

		} catch (IOException e) {
			System.err.println("Error! I/O error with the Simulator! ( 0x02)");
			System.err.println("    " + e );
		}
	}

	public void write( String s ) throws IOException {
		this.stdin.write( s + "\r\n" );
		this.stdin.flush();
		System.out.println("< " + s);
	}

	public void setup() {
		for ( int i = 0; i < this.players.size(); ++i ) {
			try {
				this.write(this.players.get(i).toString());
				this.write(".");
			} catch (IOException e) {
				System.err.println("Error! I/O error with the Simulator! (0x01)");
				System.err.println("    " + e );
			}
		}

		try {
			this.write(".");
		} catch (IOException e) {
			System.err.println("Error! I/O error with the Simulator! (0x03)");
			System.err.println("    " + e );
		}

	}

	public boolean isRunning() {
		try {
			this.littleguy.exitValue();
			return false;
		} catch ( IllegalThreadStateException e ) {
			return true;
		}
	}

	public void purge() {
		// purge logs
		try {
			while ( this.stdout.ready() ) {
				String line = this.stdout.readLine();
				if ( line != null )
					System.out.println("> " + line);
			}
		} catch (IOException e) {
			System.err.println("Error! I/O error with the Simulator! (0xB0)");
			System.err.println("    " + e);
		}
	}

	@Override
	public void run() {
		while ( this.isRunning() ) {
			try {
				String line = this.stdout.readLine();
				if ( line != null )
					System.out.println("> " + line);

			} catch (IOException e) {
				System.err.println("Error! I/O error with the Simulator! (0x00)");
				System.err.println("    " + e);
			}
		}
	}
}
